package czk.concrent.enjoyModelWithNotLock.phaser;

import java.util.concurrent.Phaser;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

/**
 * @author chenzhangkun
 * @ClassName PhaserStage
 * @description: TODO
 * @date 2024年12月04日
 */
public class PhaserStage {
	public static void main(String[] args) {

		Phaser phaser = new Phaser(3) {

			@Override
			protected boolean onAdvance(int phase, int registeredParties) {
				System.out.println("第" + phase + "阶段任务完成");
				return false;
			}
		};

		Runnable r = () -> {
			for (int i = 0; i < 3; i++) {
				try {
					System.out.println("开始做任务了");
					// 模拟每个任务的执行时间
					TimeUnit.SECONDS.sleep(ThreadLocalRandom.current().nextInt(20));
					System.out.println("完成任务了");
					phaser.arriveAndAwaitAdvance();
				} catch (InterruptedException e) {
					throw new RuntimeException(e);
				}
			}
			// 解除线程的注册
			phaser.arriveAndDeregister();
		};

		for (int i = 0; i < 3; i++) {
			new Thread(r).start();

		}
		System.out.println("完成所有阶段");

	}


}
